package com.xzm.ybr.flutter_honor_push;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;

import com.hihonor.push.sdk.HonorPushCallback;
import com.hihonor.push.sdk.HonorPushClient;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/**
 * FlutterHonorPushPlugin
 */
public class FlutterHonorPushPlugin implements FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel channel;

    private Context context;

    private FlutterHonorPushPlugin honorInstanceId;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flutter_honor_push");
        channel.setMethodCallHandler(this);
        this.context = flutterPluginBinding.getApplicationContext();
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        if (call.method.equals("getPlatformVersion")) {
            result.success("Android " + android.os.Build.VERSION.RELEASE);
        } else if (call.method.equals("honorInit")) {
            HonorPushClient.getInstance().init(context, true);
            result.success("通知初始化");
        } else if (call.method.equals("checkSupport")) {
            boolean isSupport = HonorPushClient.getInstance().checkSupportHonorPush(context);
            result.success("荣耀支持:" + String.valueOf(isSupport));
        } else if (call.method.equals("getPushToken")) {
            getToken(result);
//            result.success("获取token");
        } else if (call.method.equals("getStatus")) {
            honorInstanceId.getToken(result);
            result.success("查询状态");
        } else if (call.method.equals("turnOn")) {
            HonorPushClient.getInstance().turnOnNotificationCenter(new HonorPushCallback<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    // TODO: 打开应用通知栏状态成功
                    result.success("打开通知:成功");
                }

                @Override
                public void onFailure(int errorCode, String errorString) {
                    // TODO: 打开应用通知栏状态失败
                    result.success("打开通知:失败" + errorString);
                }
            });
            result.success("打开通知");
        } else if (call.method.equals("turnOff")) {
            HonorPushClient.getInstance().turnOffNotificationCenter(new HonorPushCallback<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    // TODO: 关闭应用通知栏状态成功
                    result.success("关闭通知:成功");
                }

                @Override
                public void onFailure(int errorCode, String errorString) {
                    // TODO: 关闭应用通知栏状态失败
                    result.success("关闭通知:失败" + errorString);
                }
            });
            result.success("关闭通知");
        } else {
            result.notImplemented();
        }
    }

    public void getToken(@NonNull Result result) {
        new Thread(() -> {
            HonorPushClient.getInstance().getPushToken(new HonorPushCallback<String>() {
                @Override
                public void onSuccess(String pushToken) {
                    // TODO: 新Token处理
                    Log.d("荣耀", "token:" + pushToken);
                    result.success("token:"+ pushToken);
                }

                @Override
                public void onFailure(int errorCode, String errorString) {
                    // TODO: 错误处理
                    Log.d("荣耀", "errorCode:" + String.valueOf(errorCode) + "error:" + errorString);
                    result.success(errorString);
                }
            });
//            hmsLogger.startMethodExecutionTimer("getToken");
//            try {
//                String defaultScope = scope == null ? Core.DEFAULT_TOKEN_SCOPE : scope;
//                if (defaultScope.trim().isEmpty()) {
//                    defaultScope = Core.DEFAULT_TOKEN_SCOPE;
//                }
//                token = HmsInstanceId.getInstance(context).getToken(appId, defaultScope);
//                hmsLogger.sendSingleEvent("getToken");
//                Utils.sendIntent(context, PushIntent.TOKEN_INTENT_ACTION, PushIntent.TOKEN, token);
//            } catch (ResolvableApiException e) {
//                hmsLogger.sendSingleEvent("getToken", String.valueOf(e.getStatusCode()));
//                PendingIntent resolution = e.getResolution();
//                if (resolution != null) {
//                    try {
//                        hmsLogger.sendSingleEvent("getToken");
//                        resolution.send();
//                    } catch (PendingIntent.CanceledException ex) {
//                        HMSLogger.getInstance(PluginContext.getContext()).sendSingleEvent("onTokenError", ex.getMessage());
//                    }
//                }
//                Intent resolutionIntent = e.getResolutionIntent();
//                if (resolutionIntent != null) {
//                    hmsLogger.sendSingleEvent("getToken");
//                    resolutionIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    PluginContext.getContext().startActivity(resolutionIntent);
//                }
//            } catch (ApiException e) {
//                hmsLogger.sendSingleEvent("getToken", String.valueOf(e.getStatusCode()));
//                Utils.sendIntent(context, PushIntent.TOKEN_INTENT_ACTION, PushIntent.TOKEN_ERROR,
//                        e.getLocalizedMessage());
//            } catch (Exception e) {
//                hmsLogger.sendSingleEvent("getToken", Code.RESULT_UNKNOWN.code());
//                Utils.sendIntent(context, PushIntent.TOKEN_INTENT_ACTION, PushIntent.TOKEN_ERROR,
//                        e.getLocalizedMessage());
//            }
        }).start();
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }
}
